<?php
/**
 * 采购需求录入环节
 */
class procController extends baseController
{       
    public function show(){
        echo "OK in Proc::show();";
        Debug::pre($_REQUEST);
        Debug::pre($_GET);
    }
        /**
	 * 补库采购需求录入
	 */
	public function dem0()
	{
		if(is_post()) { $this->save(Demand::TYPE_SCHEME); }

		if(!$this->getRecord()){
			#若非修改计算待补库材料
			$func = function($row){ $row['ware_id'] = $row['id']; return $row; };
			$this->assign('stuffs',	array_map($func, WareHelper::getRefill()));
		}
		$this->display();
	}

	/**
	 * 专项采购需求录入
	 */
	public function dem1()
	{
		if(is_post()) { $this->save(Demand::TYPE_ADDIT); }
		$this->getRecord();
		$this->display();
	}
	
	/**
	 * 紧急采购需求录入
	 */
	public function dem2()
	{
		if(is_post()) { $this->save(Demand::TYPE_URGENT); }
		$this->getRecord();
		$this->display();
	}

	/**
	 * 取已保存的采购需求记录，修改时使用
	 */
	private function getRecord(){
		$demand_id = fetch_a_int('id');
		if($demand_id){
			$demand = $this->demandCanbeModify($demand_id);
			$items = DemandItems::getByDemand($demand_id);
			$this->assign('stuffs', $items);
			$this->assign('demand', $demand);
			$this->assign('ismodify', true);
			return true;
		}
		return false;
	}
	private function demandCanbeModify($demand_id){
		$demand = Demand::get($demand_id);
		if(!$demand){
			Show::warn('无此需求记录');
		}
		if($demand['user_id']!=UID){
			Show::warn('只创建者有权修改需求记录');
		}
		if($demand['audit_flow']!=Reviewer::AUDIT_FAIL){
			Show::warn('无法修改');
		}
		return $demand;
	}
	
	/**
	 * 需求明细列表
	 */
	public function views(){
		$where = array();
		$where[] = Lib::makeTimesRange();
		$type = fetch_a_int('type');
		if($type--) $where[] = '`type`='.$type;
		$sno = fetch_a_string('sno');
		if($sno--) $where[] = "`sno`='{$sno}'";
                
		$this->assign('list', DemandHelper::getAuthList(join(' AND ',$where)));
		$this->assign('types', DemandHelper::type2text(null, true));
		$this->display();
	}
	
	/**
	 * 需求明细表
	 */
	public function table(){
		
		$where = array('audit_flow=1');
		$where[] = Lib::makeTimesRange();
		$type = fetch_a_int('type');
		if($type--) $where[] = '`demand_type`='.$type;
                $sno = fetch_a_string('sno');
		if($sno--) $where[] = "`demand_id`IN (SELECT `id` FROM `_demand` WHERE `sno`='{$sno}')";
                
		$where = join(' AND ',$where);
		
		$count = Db::get('_DemandItems')->count()->where($where)->getCol();
		$limit = PagerHelper::split2limit($count);
		$list  = Db::get('_DemandItems')->select()->where($where)->limit($limit)
				->order('demand_id DESC, sno ASC')->getAll();
                
                foreach($list as $k=>$v){
                    $_arr = Db::get('Ware')->select('`amount` as _amount, `cordon`')->where("id={$v['ware_id']}")->getAll();                    
                    $list[$k] = array_merge($list[$k], $_arr[0]);
                }

                $this->assign('list', $list);
		$this->assign('types', DemandHelper::type2text(null, true));
		$this->display();
	}

	/**
	 * 需求明细查看
	 */
	public function view(){
//		if(!DemandHelper::hasPurview(fetch_a_int('id'))){
//			Show::warn('无权操作', url('proc-views'));
//		}
               
            
                //Debug::pre($stuffs);
		$info = DemandHelper::getDetail(fetch_a_int('id'));
		if(!$info){
			Show::warn('Demand not found!', url('proc-views'));
		}
                foreach($info['items'] as $k=>$v){
                    $_arr = Db::get('Ware')->select('`amount` as _amount, `cordon`')->where("id={$v['ware_id']}")->getAll();                    
                    $info['items'][$k] = array_merge($info['items'][$k], $_arr[0]);
                }                           
                
		//Debug::pre($info);
		$this->assign('demand', $info);
		$this->assign('reviewers', ReviewerHelper::getList(Reviewer::CLS_DEMAND, fetch_a_int('id')));
		$this->assign('reviewer_back', ReviewerHelper::getBackups(Reviewer::CLS_DEMAND, fetch_a_int('id')));
		$this->display();
	}

	/** 保存采购需求 */
	protected function save($demand_type)
	{
		if(!isset($_POST['amount'])) $_POST['amount'] = array();
		if(!isset($_POST['remark'])) $_POST['remark'] = array();
		if(!isset($_POST['remark_use'])) $_POST['remark_use'] = array();

		$data	= array();
		$amount	= 0;
		foreach($_POST['amount'] as $stuff_id => $_) {
			if(empty($_POST['amount'][$stuff_id])){
				continue;
			}
			$data[$stuff_id]	= array(
				'amount'	=> intval($_POST['amount'][$stuff_id]),
				'remark'	=> FilterHelper::strip(fetch_a_string($stuff_id, $_POST['remark'])),
				'remark_use' => FilterHelper::strip(fetch_a_string($stuff_id, $_POST['remark_use'])),
			);
			$amount	+= $data[$stuff_id]['amount'];
		}
		
		if($data) {
			Db::get('Demand')->trans()->on();

			/*
			 * 修改旧记录，删除材料明细，修改记录审核状态； audit_flow/amount/total
			 * 保存并清空旧审批明细；
			 */
			$demand_id = fetch_a_int('demand_id');
			if($demand_id){
				$demand = $this->demandCanbeModify($demand_id);
				if(!DemandItems::deleteByDemand($demand_id)){
					Db::get()->trans()->rollback();
					Show::warn('删除旧材料记录失败');
				}
				if(!Demand::update($demand_id, array(
					'audit_flow' => Reviewer::AUDIT_NONE,
					'amount'	=> $amount,
					))){
						Db::get()->trans()->rollback();
						Show::warn('更新总记录失败');
				}
				if(!ReviewerHelper::backupAndClean(Reviewer::CLS_DEMAND, $demand_id)){
					Db::get()->trans()->rollback();
					Show::warn('保存审批记录失败');
				}
			}
			else{
				$demand_id = Demand::add(array(
					'type'		=> $demand_type,
					'audit_flow' => Reviewer::AUDIT_NONE,
					'sno'		=> Sno::cgen('demand'),
					'amount'	=> $amount,
					'user_id'	=> UID,
					'dept_id'	=> fetch_a_int('dept_id'),
					'addtime'	=> time(),
					'sum_month'	=> date('Ym'),
				));
				if(!$demand_id) {
					Db::get()->trans()->rollback();
					Show::warn("保存采购需求信息失败！");
				}
			}

			foreach($data as $stuff_id=>$row) {
				$stuff	= Ware::getbyid($stuff_id);
				if(!DemandItems::add(array(
					'demand_id'	=> $demand_id,
					'ware_id'	=> $stuff['id'],
					'class_id'	 => $stuff['class_id'],
					'class_path' => $stuff['class_path'],
					'sno'		=> $stuff['sno'],
					'name'		=> $stuff['name'],
					'brand'		=> $stuff['brand'],
					'specific'	=> $stuff['specific'],
					'unit'		=> $stuff['unit'],
					'amount'	=> $row['amount'],
					'remark'	=> $row['remark'],
					'remark_use' => $row['remark_use'],
				))){
					Db::get()->trans()->rollback();
					Show::warn("保存采购需求明细失败！");
				}
			}

			#增加审批人记录
			if(!ReviewerHelper::expand(Reviewer::CLS_DEMAND, $demand_id, fetch_a_int('dept_id'))){
				Db::get()->trans()->rollback();
				Show::warn(ReviewerHelper::getLastError());
			}

			Db::get()->trans()->commit();
			
			Show::note('保存成功', url("proc-dem{$demand_type}"));
		}
		else {
			Show::warn('请输入正确的采购信息');
		}
	}
        
        /**
	 * Ajax请求关闭单条反馈显示
	 */
        public function closefeedback()
        {
            $id = fetch_a_int('id');
            $isOK = false;
            if($id)
            {
               $isOK = Demand::update($id, array('isview' => 'yes')); 
            }
            
            $arr = array('isOK'=>$isOK?'true':'false');
            echo json_encode($arr);
            die;
        }
}

?>
